Swift 从文本文件中读取和写入字符串

您所在的位置:网站首页 swift files Swift 从文本文件中读取和写入字符串

Swift 从文本文件中读取和写入字符串

2024-07-09 22:55| 来源: 网络整理| 查看: 265

Swift 从文本文件中读取和写入字符串

在Swift中,你可以使用String类的String(contentsOfFile:)和write(toFile:atomically:encoding:)方法从文本文件中读写一个字符串。你将看到一些在Swift中读和写文件的例子。

String(contentsOfFile:)

String类提供了一个从文件内容创建字符串的类方法。这个方法是一个初始化器,必须给出文件的路径。例如,你可以通过传递路径给主捆绑器来读取本地文件的内容。这个过程会返回一个包含文件内容的新字符串。

请记住,如果内容或路径无效或有其他原因,这个方法可能会返回nil。可以使用try-catch块来管理这种情况。

write(toFile:atomically:encoding:)

在这个方法中,字符串类的一个实例将字符串的内容写到一个文件中。该方法需要三个参数 –

toFile - 要写入字符串的文件路径。

atomically - 一个布尔值,决定文件是否应该被原子化地写入。如果设置为 “true”,文件会被写到一个临时位置,然后重命名到最终位置。这可以帮助防止在写操作中出现故障时的数据丢失。

encoding - 将字符串写入文件时要使用的编码。默认值是.utf8。

下面是一个如何从文本文件中读取字符串的例子

在跳转到读取文件之前,请注意这里。在这里,我们在Xcode项目中添加了一个名字为 “example.txt “的文件。我们将读取同一个文件。在该文本文件中,我们添加了字符串内容,其内容如下-

Lorem Ipsum是印刷和排版行业的简单假文本。

自15世纪以来,Lorem Ipsum一直是行业内的标准假文本,当时一个不知名的印刷商拿着一版印刷品,把它弄得乱七八糟,做成了一本字体标本。

例子

同样的字符串内容将从example.txt文件中读出 —

func readString() { do { // creating a path from the main bundle if let bundlePath = Bundle.main.path(forResource: "example.txt", ofType: nil) { let stringContent = try String(contentsOfFile: bundlePath) print("Content string starts from here-----") print(stringContent) print("End at here-----") } } catch { print(error) } } 输出 Content string starts from here----- Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. End at here----- 而这里是一个如何将字符串写入文本文件的例子

为了将字符串内容写入文件,我们将使用上述例子中使用的相同文件。

例子 func writeString() { do { // creating path from main bundle if let bundlePath = Bundle.main.path(forResource: "example.txt", ofType: nil) { let stringToWrite = "This is a string to write to a file." try? stringToWrite.write(toFile: bundlePath, atomically: true, encoding: .utf8) let stringContent = try String(contentsOfFile: bundlePath) print("Content string starts from here-----") print(stringContent) print("End at here-----") } } catch { print(error) } } 输出 Content string starts from here----- This is a string to write to a file. End at here-----

注意,bundlePath变量是bundle中的文件的路径。如果文件不在bundle中,你也可以使用一个自定义路径。

请记住 contentsOfFile:和 write(toFile:atomically:encoding:) 方法会产生错误,所以建议使用 try?关键字或do-catch语句来处理它们。

总结

上述方法用于将文件的内容读成字符串,然后将字符串写入文件。

你应该注意,当你处理文件的时候,需要处理错误。这是因为在读或写文件时,有更多的机会出现错误。你可以提供一个可能是自定义的路径或捆绑文件中的一个路径。此外,你还可以使用FileManager提供文件系统的路径。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3